import { Awaited } from "../../apis";
import api from "../../apis/activity";
import {formatByDot, formatDateToYYYYMMDD, formatTime} from "../../utils/dateUtil";

const ACTIVITY_INDEX = 0;
const ANNOUNCEMENT_INDEX = 1;

Page({
  onSearch(e) {
    this.setData({
      currentSearch: e.detail,
    })
    this.onRefresh();
  },
  onFilterChange(e) {
    this.setData({
      currentFilter: e.detail,
    })
    this.onRefresh();
  },
  data: {
    currentSearch: "",
    shouldScrollViewMaskShow: false,

    header: ["活动", "公告"],

    activityHeaderSelectedIndex: ACTIVITY_INDEX,
    cardListLayout: [
      [],
      []
    ],
    currentFilter: [],
    filterBarLayout: [
      {
        displayText: 0,
        displayIcons: {
          left: "position"
        },
        autoHide: true,
        filters: [{
          key: "locations",
          type: "text",
          name: 0,
          defaultIndices: [0],
          options: ["全部校区", "北洋园", "卫津路"],
          optionsValue: [
            null, 1, 0
          ],
        }],
      },
      {
        displayText: 0,
        autoHide: true,
        filters: [{
          key: "sort_by",
          type: "text",
          name: 0,
          defaultIndices: [0],
          options: ["最新发布", "最近活动"],
          optionsValue: [0, 1],
        }],
      },
      // {
      //   displayText: 0,
      //   autoHide: true,
      //   filters: [
      //     {
      //       type: "date",
      //       name: "日期",
      //     }
      //   ],
      // },
      {
        displayText: "筛选",
        alignRight: true,
        resettable: true,
        filters: [{
          key: "categories",
          type: "tag",
          multiple: true,
          showHeaderText: true,
          headerText: "活动类型",
          options: ["科创", "生活", "就业", "社团", "讲座", "展览", "实验招募"],
          optionsValue: [0, 1, 2, 3, 4, 5, 6],
        },
          // {
          //   type: "tag",
          //   multiple: true,
          //   showHeaderText: true,
          //   headerText: "组织单位",
          //   options: ["图书馆", "团委", "保卫处"]
          // }
        ]
      }
    ],

    footerLayout: [{
      url: "home/index",
      label: "主页",
      icon: "home"
    },
      {
        url: 'activity/index',
        label: "动态",
        icon: "activity"
      },
      //   {
      //   url: 'help/index',
      //   label: "互助",
      //   icon: "help"
      // }, {
      //   url: 'portal/index',
      //   label: "传送",
      //   icon: "portal"
      // },
      {
        url: "me/index",
        label: "我的",
        icon: "me"
      }
    ],
    page: 1,
    len: 15,
    hasNext: true
  },
  // Tab Bar switch
  onTabChange: function (e) {
    this.setData({
      current: e.currentTarget.dataset.id
    })
  },
  onFilterDropDownToggle(e) {
    this.setData({
      shouldScrollViewMaskShow: e.detail.hasFilterDropdownShown
    })
  },
  onActivityHeaderSelected(e) {
    this.setData({
      activityHeaderSelectedIndex: e.detail.id,
      "filterBarLayout[1].filters[0].options[1]": e.detail.id === 0 ? "最近活动" : "最早发布",
      page: 1,
    })
    this.onRefresh();
  },
  onFooterSelected(e) {
    // todo!(); TODO:
  },
  addList(res: Awaited<ReturnType<typeof api.getActivityList>> | Awaited<ReturnType<typeof api.getAnnouncementList>>, clear = false) {
    // console.warn(res);
    const daysMapping = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    const tagMapping = ["科创", "生活", "就业", "社团", "讲座", "展览", "实验招募"];
    let tab = this.data.activityHeaderSelectedIndex;
    this.setData({
      page: res.current_page,
      hasNext: res["has_next"],
      [`cardListLayout[${tab}]`]: [
        ...!clear ? this.data.cardListLayout[tab] : [],
        ...res.data.map(element => {
          let date = new Date(element.date_time);
          if (tab === 0)
            return {
              id: element.id,
              image: element["poster"] ?? "/assets/poster.png",
              title: element.name,
              tags: [tagMapping[element["type_id"]]],
              datetime: {
                date: formatDateToYYYYMMDD(date),
                day: daysMapping[date.getDay()],
                time: formatTime(date),
              },
              avatar: element["publisher_avatar"] ?? "/assets/poster.png",
              organizer: element["publisher_name"],
              variant: "activity",
              status: new Date().getTime() <= new Date(element.submission_deadline).getTime() ? {
                name: "报名中",
                color: "#F27D11"
              } : {
                name: "已结束",
                color: "#666666"
              }
            };
          else
            return {
              id: element.id,
              image: element["poster"] ?? "/assets/poster.png",
              title: element.name,
              tags: [tagMapping[element["type_id"]]],
              datetime: {
                date: formatByDot(new Date(element.date_time)),
              },
              avatar: element["publisher_avatar"] ?? "/assets/poster.png",
              organizer: element["publisher_name"],
              variant: "announcement",
            }
        })
      ]
    })
  },
  addActivityList(res: Awaited<ReturnType<typeof api.getActivityList>>, clear = false) {
    const daysMapping = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    const tagMapping = ["科创", "生活", "就业", "社团", "讲座", "展览", "实验招募"];
    let tab = this.data.activityHeaderSelectedIndex;
    this.setData({
      page: res.current_page,
      hasNext: res["has_next"],
      [`cardListLayout[${ACTIVITY_INDEX}]`]: [
        ...!clear ? this.data.cardListLayout[tab] : [],
        ...res.data.map(element => {
          let date = new Date(element.date_time);
          return {
            id: element.id,
            image: element["poster"] ?? "/assets/poster.png",
            title: element.name,
            tags: [tagMapping[element["type_id"]]],
            datetime: {
              date: formatDateToYYYYMMDD(date),
              day: daysMapping[date.getDay()],
              time: formatTime(date),
            },
            avatar: element["publisher_avatar"] ?? "/assets/poster.png",
            organizer: element["publisher_name"],
            variant: "activity",
            status: new Date().getTime() <= new Date(element.submission_deadline).getTime() ? {
              name: "报名中",
              color: "#F27D11"
            } : {
              name: "已结束",
              color: "#666666"
            }
          };
        })
      ]
    })
  },
  addAnnouncementList(res: Awaited<ReturnType<typeof api.getAnnouncementList>>, clear = false) {
    console.warn(res);
    const daysMapping = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    const tagMapping = ["科创", "生活", "就业", "社团", "讲座", "展览", "实验招募"];
    this.setData({
      page: res.current_page,
      hasNext: res["has_next"],
      [`cardListLayout[${ANNOUNCEMENT_INDEX}]`]: [
        ...!clear ? this.data.cardListLayout[ANNOUNCEMENT_INDEX] : [],
        ...res.data.map(element => {
          let date = new Date(element.date_time);
          return {
            id: element.id,
            image: element["poster"] ?? "/assets/poster.png",
            title: element.name,
            tags: [tagMapping[element["type_id"]]],
            datetime: {
              date: formatByDot(new Date(element.date_time)),
            },
            avatar: element["publisher_avatar"] ?? "/assets/poster.png",
            organizer: element["publisher_name"],
            variant: "announcement",
          }
        })
      ]
    })
  },
  async loadMoreActivity() {
    if (!this.data.hasNext) return;
    const res = await api.getActivityList(this.data.page + 1, this.data.len, this.data.currentFilter, this.data.currentSearch);
    this.addList(res, false);
  },
  async refreshActivity() {
    const res = await api.getActivityList(1, this.data.len, this.data.currentFilter, this.data.currentSearch);
    this.addList(res, true);
    this.selectComponent(".activity-card-list-wrapper").finishRefresh();
  },
  async refreshAnnouncement() {
    const res = await api.getAnnouncementList(1, this.data.len, this.data.currentFilter, this.data.currentSearch);
    this.addList(res, true);
    this.selectComponent(".activity-card-list-wrapper").finishRefresh();
  },
  async loadMoreAnnouncement() {
    if (!this.data.hasNext) return;
    const res = await api.getAnnouncementList(this.data.page + 1, this.data.len, this.data.currentFilter, this.data.currentSearch);
    this.addList(res);
  },
  onRefresh() {
    if (this.data.activityHeaderSelectedIndex === 0) this.refreshActivity();
    else this.refreshAnnouncement();
  },
  loadMore() {
    // console.log(this.data.activityHeaderSelectedIndex)
    if (this.data.activityHeaderSelectedIndex === 0) this.loadMoreActivity();
    else this.loadMoreAnnouncement();
  },
  async onLoad() {
    this.setData({
      currentFilter: this.selectComponent(".search-section-wrapper").getFilter()
    })
    this.onRefresh();
  }
})
